package com.gjy.amqp.simple.consumer;

import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-05-17 10:22:47
 */
public class DirectLogConsumer {

    private static final String EXCHANGE_NAME = "direct_logs";
    private static final String ROUTING_KEY = "info";
    private static final Logger log = LoggerFactory.getLogger(DirectLogConsumer.class);

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.253.142");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        String queue = channel.queueDeclare().getQueue();
        channel.queueBind(queue, EXCHANGE_NAME, ROUTING_KEY);

        channel.basicConsume(queue, true, new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                log.info("key: {}", message.getEnvelope().getRoutingKey());
                log.info("msg: {}", new String(message.getBody(), StandardCharsets.UTF_8));
            }
        }, new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        });
    }

}
